import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox, QStackedWidget,
                             QGroupBox, QFormLayout, QDialog, QTabWidget, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QTextEdit, QGridLayout,
                             QSpinBox, QRadioButton, QButtonGroup)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration2_student_management.create_student import StudentCreator
from iteration2_student_management.query_student import StudentQuery
from iteration2_student_management.delete_student import StudentDeleter
from iteration2_student_management.update_student import StudentUpdater

# 学生创建窗口
class CreateStudentDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('新建学生信息')
        self.setGeometry(300, 300, 400, 300)
        self.creator = StudentCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.student_id_input = QLineEdit()
        self.student_id_input.setPlaceholderText('例如: 20210001')
        form_layout.addRow('学号:', self.student_id_input)
        
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText('例如: 张三')
        form_layout.addRow('姓名:', self.name_input)
        
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(['男', '女'])
        form_layout.addRow('性别:', self.gender_combo)
        
        self.class_input = QLineEdit()
        self.class_input.setPlaceholderText('例如: 计算机2021-1班')
        form_layout.addRow('班级:', self.class_input)
        
        self.contact_input = QLineEdit()
        self.contact_input.setPlaceholderText('例如: 13800138000')
        form_layout.addRow('联系方式:', self.contact_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('学生信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('创建')
        self.create_button.clicked.connect(self.create_student)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def create_student(self):
        student_id = self.student_id_input.text().strip()
        name = self.name_input.text().strip()
        gender = self.gender_combo.currentText()
        class_name = self.class_input.text().strip()
        contact = self.contact_input.text().strip() or None
        
        if not student_id or not name or not class_name:
            QMessageBox.warning(self, '警告', '学号、姓名和班级不能为空')
            return
        
        result = self.creator.create_student(student_id, name, gender, class_name, contact)
        
        if result:
            QMessageBox.information(self, '成功', f'学生 {name} 信息创建成功')
            self.accept()

# 批量创建学生窗口
class BatchCreateStudentDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('批量新建学生信息')
        self.setGeometry(300, 300, 500, 400)
        self.creator = StudentCreator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 说明标签
        instruction_label = QLabel('每行输入一个学生信息，格式：学号,姓名,性别,班级,联系方式(可选)')
        instruction_label.setWordWrap(True)
        layout.addWidget(instruction_label)
        
        # 文本输入区域
        self.text_input = QTextEdit()
        self.text_input.setPlaceholderText('例如:\n20210001,张三,男,计算机2021-1班,13800138000\n20210002,李四,女,计算机2021-1班')
        layout.addWidget(self.text_input)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.create_button = QPushButton('批量创建')
        self.create_button.clicked.connect(self.batch_create_students)
        button_layout.addWidget(self.create_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def batch_create_students(self):
        text = self.text_input.toPlainText().strip()
        if not text:
            QMessageBox.warning(self, '警告', '请输入学生信息')
            return
        
        lines = text.split('\n')
        students_data = []
        
        for line in lines:
            parts = [part.strip() for part in line.split(',')]
            if len(parts) < 4:
                QMessageBox.warning(self, '警告', f'格式错误: {line}\n请确保至少包含学号、姓名、性别和班级')
                return
            
            student_id = parts[0]
            name = parts[1]
            gender = parts[2]
            class_name = parts[3]
            contact = parts[4] if len(parts) > 4 else None
            
            students_data.append((student_id, name, gender, class_name, contact))
        
        if students_data:
            success_count, total_count = self.creator.batch_create_students(students_data)
            QMessageBox.information(self, '成功', f'批量创建完成：成功 {success_count}/{total_count}')
            self.accept()

# 学生查询窗口
class QueryStudentWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.query = StudentQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询选项
        option_group = QGroupBox('查询选项')
        option_layout = QVBoxLayout()
        
        self.query_all_btn = QRadioButton('查询所有学生')
        self.query_all_btn.setChecked(True)
        option_layout.addWidget(self.query_all_btn)
        
        self.query_by_id_btn = QRadioButton('根据学号查询学生')
        option_layout.addWidget(self.query_by_id_btn)
        
        self.query_by_name_btn = QRadioButton('根据姓名查询学生')
        option_layout.addWidget(self.query_by_name_btn)
        
        self.query_by_class_btn = QRadioButton('根据班级查询学生')
        option_layout.addWidget(self.query_by_class_btn)
        
        self.query_by_dormitory_btn = QRadioButton('根据宿舍查询学生')
        option_layout.addWidget(self.query_by_dormitory_btn)
        
        # 创建按钮组
        self.query_button_group = QButtonGroup()
        self.query_button_group.addButton(self.query_all_btn, 1)
        self.query_button_group.addButton(self.query_by_id_btn, 2)
        self.query_button_group.addButton(self.query_by_name_btn, 3)
        self.query_button_group.addButton(self.query_by_class_btn, 4)
        self.query_button_group.addButton(self.query_by_dormitory_btn, 5)
        
        option_group.setLayout(option_layout)
        layout.addWidget(option_group)
        
        # 查询参数表单
        self.param_group = QGroupBox('查询参数')
        self.param_layout = QFormLayout()
        
        self.student_id_input = QLineEdit()
        self.student_id_input.setPlaceholderText('例如: 20210001')
        self.param_layout.addRow('学号:', self.student_id_input)
        
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText('例如: 张三')
        self.param_layout.addRow('姓名:', self.name_input)
        
        self.class_input = QLineEdit()
        self.class_input.setPlaceholderText('例如: 计算机2021-1班')
        self.param_layout.addRow('班级:', self.class_input)
        
        # 获取所有宿舍信息
        db = Database()
        db.connect()
        db.cursor.execute(
            "SELECT id, building, room_number FROM dormitory ORDER BY building, room_number"
        )
        dormitories = db.cursor.fetchall()
        db.close()
        
        # 宿舍选择下拉框
        self.dormitory_combo = QComboBox()
        self.dormitory_combo.addItem('-- 选择宿舍 --', None)
        for dorm in dormitories:
            self.dormitory_combo.addItem(f"{dorm[1]}-{dorm[2]}", dorm[0])
        self.param_layout.addRow('宿舍:', self.dormitory_combo)
        
        self.param_group.setLayout(self.param_layout)
        self.param_group.setVisible(False)
        layout.addWidget(self.param_group)
        
        # 查询按钮
        self.query_btn = QPushButton('查询')
        self.query_btn.clicked.connect(self.perform_query)
        layout.addWidget(self.query_btn)
        
        # 结果表格
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(7)
        self.result_table.setHorizontalHeaderLabels(['学生ID', '学号', '姓名', '性别', '班级', '联系方式', '宿舍ID'])
        self.result_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.result_table)
        
        # 连接信号
        self.query_button_group.buttonClicked.connect(self.on_query_option_changed)
        
        self.setLayout(layout)
    
    def on_query_option_changed(self, button):
        # 隐藏所有输入框
        for i in range(self.param_layout.rowCount()):
            self.param_layout.itemAt(i * 2 + 1).widget().setVisible(False)
            self.param_layout.itemAt(i * 2).widget().setVisible(False)
        
        # 根据选择的查询方式显示相应的输入框
        if button == self.query_by_id_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(0).widget().setVisible(True)  # 学号标签
            self.param_layout.itemAt(1).widget().setVisible(True)  # 学号输入框
        elif button == self.query_by_name_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(2).widget().setVisible(True)  # 姓名标签
            self.param_layout.itemAt(3).widget().setVisible(True)  # 姓名输入框
        elif button == self.query_by_class_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(4).widget().setVisible(True)  # 班级标签
            self.param_layout.itemAt(5).widget().setVisible(True)  # 班级输入框
        elif button == self.query_by_dormitory_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(6).widget().setVisible(True)  # 宿舍标签
            self.param_layout.itemAt(7).widget().setVisible(True)  # 宿舍下拉框
        else:
            self.param_group.setVisible(False)
    
    def perform_query(self):
        selected_option = self.query_button_group.checkedId()
        
        if selected_option == 1:  # 查询所有学生
            students = self.query.query_all_students()
            self.display_results(students)
        
        elif selected_option == 2:  # 根据学号查询学生
            student_id = self.student_id_input.text().strip()
            
            if not student_id:
                QMessageBox.warning(self, '警告', '学号不能为空')
                return
            
            student = self.query.query_student_by_id(student_id)
            
            if student:
                self.display_results([student])
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到学号为 {student_id} 的学生')
        
        elif selected_option == 3:  # 根据姓名查询学生
            name = self.name_input.text().strip()
            
            if not name:
                QMessageBox.warning(self, '警告', '姓名不能为空')
                return
            
            students = self.query.query_student_by_name(name)
            
            if students:
                self.display_results(students)
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到姓名为 {name} 的学生')
        
        elif selected_option == 4:  # 根据班级查询学生
            class_name = self.class_input.text().strip()
            
            if not class_name:
                QMessageBox.warning(self, '警告', '班级不能为空')
                return
            
            students = self.query.query_student_by_class(class_name)
            
            if students:
                self.display_results(students)
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到班级为 {class_name} 的学生')
        
        elif selected_option == 5:  # 根据宿舍查询学生
            dormitory_id = self.dormitory_combo.currentData()
            
            if not dormitory_id:
                QMessageBox.warning(self, '警告', '请选择宿舍')
                return
            
            try:
                students = self.query.query_student_by_dormitory(dormitory_id)
                
                if students:
                    self.display_results(students)
                else:
                    self.result_table.setRowCount(0)
                    dorm_text = self.dormitory_combo.currentText()
                    QMessageBox.information(self, '提示', f'没有找到宿舍 {dorm_text} 的学生')
            except Exception as e:
                QMessageBox.warning(self, '警告', f'查询出错: {str(e)}')
    
    def display_results(self, students):
        if not students:
            self.result_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何学生信息')
            return
        
        self.result_table.setRowCount(len(students))
        
        for row, student in enumerate(students):
            self.result_table.setItem(row, 0, QTableWidgetItem(str(student[0])))
            self.result_table.setItem(row, 1, QTableWidgetItem(student[1]))
            self.result_table.setItem(row, 2, QTableWidgetItem(student[2]))
            self.result_table.setItem(row, 3, QTableWidgetItem(student[3]))
            self.result_table.setItem(row, 4, QTableWidgetItem(student[4]))
            self.result_table.setItem(row, 5, QTableWidgetItem(student[5] or '-'))
            self.result_table.setItem(row, 6, QTableWidgetItem(str(student[6]) if student[6] else '未分配'))

# 学生删除窗口
class DeleteStudentWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.deleter = StudentDeleter()
        self.query = StudentQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有学生
        self.refresh_btn = QPushButton('刷新学生列表')
        self.refresh_btn.clicked.connect(self.refresh_student_list)
        layout.addWidget(self.refresh_btn)
        
        # 学生列表
        self.student_table = QTableWidget()
        self.student_table.setColumnCount(7)
        self.student_table.setHorizontalHeaderLabels(['学生ID', '学号', '姓名', '性别', '班级', '联系方式', '宿舍ID'])
        self.student_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.student_table.setSelectionBehavior(QTableWidget.SelectRows)
        layout.addWidget(self.student_table)
        
        # 删除按钮
        button_layout = QHBoxLayout()
        
        self.delete_single_btn = QPushButton('删除选中学生')
        self.delete_single_btn.clicked.connect(self.delete_selected_student)
        button_layout.addWidget(self.delete_single_btn)
        
        self.delete_batch_btn = QPushButton('批量删除选中学生')
        self.delete_batch_btn.clicked.connect(self.batch_delete_students)
        button_layout.addWidget(self.delete_batch_btn)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
        # 初始加载学生列表
        self.refresh_student_list()
    
    def refresh_student_list(self):
        students = self.query.query_all_students()
        
        if not students:
            self.student_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何学生信息')
            return
        
        self.student_table.setRowCount(len(students))
        
        for row, student in enumerate(students):
            self.student_table.setItem(row, 0, QTableWidgetItem(str(student[0])))
            self.student_table.setItem(row, 1, QTableWidgetItem(student[1]))
            self.student_table.setItem(row, 2, QTableWidgetItem(student[2]))
            self.student_table.setItem(row, 3, QTableWidgetItem(student[3]))
            self.student_table.setItem(row, 4, QTableWidgetItem(student[4]))
            self.student_table.setItem(row, 5, QTableWidgetItem(student[5] or '-'))
            self.student_table.setItem(row, 6, QTableWidgetItem(str(student[6]) if student[6] else '未分配'))
    
    def delete_selected_student(self):
        selected_rows = self.student_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的学生')
            return
        
        row = selected_rows[0].row()
        student_id = self.student_table.item(row, 1).text()
        name = self.student_table.item(row, 2).text()
        
        reply = QMessageBox.question(self, '确认删除', 
                                    f'确定要删除学生 {name} (学号: {student_id}) 吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.deleter.delete_student(student_id)
            
            if result:
                QMessageBox.information(self, '成功', f'学生 {name} 已删除')
                self.refresh_student_list()
    
    def batch_delete_students(self):
        selected_rows = self.student_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的学生')
            return
        
        student_ids = []
        student_names = []
        
        for model_index in selected_rows:
            row = model_index.row()
            student_id = self.student_table.item(row, 1).text()
            name = self.student_table.item(row, 2).text()
            student_ids.append(student_id)
            student_names.append(f"{name} (学号: {student_id})")
        
        reply = QMessageBox.question(self, '确认批量删除', 
                                    f'确定要删除选中的 {len(student_ids)} 个学生吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            success_count, total_count = self.deleter.batch_delete_students(student_ids)
            QMessageBox.information(self, '成功', f'批量删除完成：成功 {success_count}/{total_count}')
            self.refresh_student_list()

# 学生更新窗口
class UpdateStudentWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.updater = StudentUpdater()
        self.query = StudentQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有学生
        self.refresh_btn = QPushButton('刷新学生列表')
        self.refresh_btn.clicked.connect(self.refresh_student_list)
        layout.addWidget(self.refresh_btn)
        
        # 学生列表
        self.student_table = QTableWidget()
        self.student_table.setColumnCount(7)
        self.student_table.setHorizontalHeaderLabels(['学生ID', '学号', '姓名', '性别', '班级', '联系方式', '宿舍ID'])
        self.student_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.student_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.student_table.itemSelectionChanged.connect(self.on_selection_changed)
        layout.addWidget(self.student_table)
        
        # 更新表单
        self.update_group = QGroupBox('更新学生信息')
        update_layout = QFormLayout()
        
        self.name_input = QLineEdit()
        update_layout.addRow('新姓名:', self.name_input)
        
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(['男', '女'])
        update_layout.addRow('新性别:', self.gender_combo)
        
        self.class_input = QLineEdit()
        update_layout.addRow('新班级:', self.class_input)
        
        self.contact_input = QLineEdit()
        update_layout.addRow('新联系方式:', self.contact_input)
        
        self.update_group.setLayout(update_layout)
        layout.addWidget(self.update_group)
        
        # 更新按钮
        self.update_btn = QPushButton('更新学生信息')
        self.update_btn.clicked.connect(self.update_student)
        self.update_btn.setEnabled(False)
        layout.addWidget(self.update_btn)
        
        self.setLayout(layout)
        
        # 初始加载学生列表
        self.refresh_student_list()
    
    def refresh_student_list(self):
        students = self.query.query_all_students()
        
        if not students:
            self.student_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何学生信息')
            return
        
        self.student_table.setRowCount(len(students))
        
        for row, student in enumerate(students):
            self.student_table.setItem(row, 0, QTableWidgetItem(str(student[0])))
            self.student_table.setItem(row, 1, QTableWidgetItem(student[1]))
            self.student_table.setItem(row, 2, QTableWidgetItem(student[2]))
            self.student_table.setItem(row, 3, QTableWidgetItem(student[3]))
            self.student_table.setItem(row, 4, QTableWidgetItem(student[4]))
            self.student_table.setItem(row, 5, QTableWidgetItem(student[5] or '-'))
            self.student_table.setItem(row, 6, QTableWidgetItem(str(student[6]) if student[6] else '未分配'))
    
    def on_selection_changed(self):
        selected_rows = self.student_table.selectionModel().selectedRows()
        self.update_btn.setEnabled(len(selected_rows) > 0)
        
        if len(selected_rows) > 0:
            row = selected_rows[0].row()
            self.name_input.setText(self.student_table.item(row, 2).text())
            gender = self.student_table.item(row, 3).text()
            self.gender_combo.setCurrentText(gender)
            self.class_input.setText(self.student_table.item(row, 4).text())
            contact = self.student_table.item(row, 5).text()
            self.contact_input.setText(contact if contact != '-' else '')
    
    def update_student(self):
        selected_rows = self.student_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要更新的学生')
            return
        
        row = selected_rows[0].row()
        student_id = self.student_table.item(row, 1).text()
        old_name = self.student_table.item(row, 2).text()
        
        name = self.name_input.text().strip()
        gender = self.gender_combo.currentText()
        class_name = self.class_input.text().strip()
        contact = self.contact_input.text().strip() or None
        
        if not name or not class_name:
            QMessageBox.warning(self, '警告', '姓名和班级不能为空')
            return
        
        reply = QMessageBox.question(self, '确认更新', 
                                    f'确定要更新学生 {old_name} (学号: {student_id}) 的信息吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.updater.update_student(student_id, name, gender, class_name, contact)
            
            if result:
                QMessageBox.information(self, '成功', f'学生 {old_name} 信息已更新')
                self.refresh_student_list()

# 学生管理主窗口
class StudentManagementWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('学生信息管理')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()
        
    def initUI(self):
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡窗口
        tab_widget = QTabWidget()
        
        # 创建学生信息管理的各个功能选项卡
        self.create_tab = QWidget()
        self.query_tab = QueryStudentWidget()
        self.delete_tab = DeleteStudentWidget()
        self.update_tab = UpdateStudentWidget()
        
        # 设置创建学生选项卡
        create_layout = QVBoxLayout()
        create_btn = QPushButton('新建学生信息')
        create_btn.setMinimumHeight(50)
        create_btn.setFont(QFont('Arial', 12))
        create_btn.clicked.connect(self.open_create_dialog)
        create_layout.addWidget(create_btn)
        
        batch_create_btn = QPushButton('批量新建学生信息')
        batch_create_btn.setMinimumHeight(50)
        batch_create_btn.setFont(QFont('Arial', 12))
        batch_create_btn.clicked.connect(self.open_batch_create_dialog)
        create_layout.addWidget(batch_create_btn)
        
        create_layout.addStretch()
        self.create_tab.setLayout(create_layout)
        
        # 添加选项卡
        tab_widget.addTab(self.create_tab, '新建学生')
        tab_widget.addTab(self.query_tab, '查询学生')
        tab_widget.addTab(self.delete_tab, '删除学生')
        tab_widget.addTab(self.update_tab, '更新学生信息')
        
        main_layout.addWidget(tab_widget)
        
        # 返回按钮
        back_btn = QPushButton('返回主菜单')
        back_btn.clicked.connect(self.close)
        main_layout.addWidget(back_btn)
    
    def open_create_dialog(self):
        dialog = CreateStudentDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.delete_tab.refresh_student_list()
            self.update_tab.refresh_student_list()
    
    def open_batch_create_dialog(self):
        dialog = BatchCreateStudentDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果创建成功，刷新其他选项卡的数据
            self.query_tab.perform_query()
            self.delete_tab.refresh_student_list()
            self.update_tab.refresh_student_list()

# 如果直接运行此文件，提供测试界面
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StudentManagementWindow()
    window.show()
    sys.exit(app.exec_())